package com.example.xiaoxueqixiangmu.jiemian;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.bean.Seat;
import com.example.xiaoxueqixiangmu.bean.Train;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class chepiaoyuding2Activity extends AppCompatActivity {
    private static final String TAG = "chepiaoyuding2Activity";
    private TextView BT1 , BT2 , TV8 , txtTrainNo , txtContent , txtT1;
    private ListView lv;
    private MyListViewAdapter2 myListViewAdapter2;
    private ArrayList<HashMap<String,String>> dataArray;
    private List<Train> listTrain;
    private String fromStationName , toStationName, startTrainDate;
    int myear;
    int mmonth;
    int mday;

    private String trainNo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chepiaoyuding2);
        dataArray = new ArrayList<>();

        // 从上一个Activity中获取参数，出发车站，到达车站，出发时间（年月日）
        fromStationName = getIntent().getStringExtra("fromStationName");
        toStationName = getIntent().getStringExtra("toStationName");
        myear = getIntent().getIntExtra("myear",0);
        mmonth = getIntent().getIntExtra("mmonth",0);
        mday = getIntent().getIntExtra("mday",0);
        trainNo = getIntent().getStringExtra("trainNo");
        startTrainDate = myear+"-"+mmonth+"-"+mday;

        // 从上一个Activity中获取火车list
        listTrain = (List<Train>)getIntent().getSerializableExtra("listTrain");

        // 初始化Layout中的组件
        txtT1 = findViewById(R.id.txtT1);
        BT2 = findViewById(R.id.BT2);
        BT1 = findViewById(R.id.BT1);
        lv =  findViewById(R.id.lv);
        TV8 = findViewById(R.id.TV8);
        TV8.setText(startTrainDate);
        String content = getIntent().getStringExtra("content");
        String transNo = getIntent().getStringExtra("transNo");
        String goCity = getIntent().getStringExtra("goCity");
        String backCity = getIntent().getStringExtra("backCity");

        txtTrainNo = findViewById(R.id.txtTrainNo);
        txtContent = findViewById(R.id.txtContent);
        txtContent.setText(content);
        txtTrainNo.setText(transNo);

        // 对火车list中的seats数据进行解析，加载到数据源List中
        Map<String,Seat> seats = (Map<String, Seat>)getIntent().getSerializableExtra("seats");
        Set<String> keySet = seats.keySet();
        Iterator<String> iterator = keySet.iterator();

        while ( iterator.hasNext() ){
            Seat seat = seats.get(iterator.next());
            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("seatName",seat.getSeatName());
            hashMap.put("seatNum",seat.getSeatNum()+"张");
            hashMap.put("price","￥ "+seat.getSeatPrice());
            dataArray.add(hashMap);
        }
        myListViewAdapter2 = new MyListViewAdapter2(this,dataArray);
        lv.setAdapter(myListViewAdapter2);

        txtT1.setText(goCity+"->"+backCity);

        // 对 ListView设置监听事件，如果某一型号的火车车次被点击，将此车次的信息传入到chepiaoActivity3中，让用户买票
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent  = new Intent(chepiaoyuding2Activity.this,chepiaoyuding3Activity.class);
                Train train = chepiaoyuding2Activity.this.listTrain.get(position);
                Map<String, Seat> seats = train.getSeats();
                intent.putExtra("seats", (Serializable) seats);
                intent.putExtra("transNo",train.getTrainNo());
                String str = train.getStartTime()+"-"+train.getArriveTime()+",历时"+train.getDurationTime();
                intent.putExtra("content",str);
                intent.putExtra("fromStationName",fromStationName);
                intent.putExtra("toStationName",toStationName);
                intent.putExtra("startTrainDate",startTrainDate);
                intent.putExtra("myear",myear);
                intent.putExtra("mmonth",mmonth);
                intent.putExtra("mday",mday);
                intent.putExtra("tn",train.getTrainNo());
                intent.putExtra("dur",train.getDurationTime());
                intent.putExtra("stt",train.getStartTime());
                intent.putExtra("at",train.getArriveTime());
                HashMap<String, String> hashMap = dataArray.get(position);

                intent.putExtra("seatName",hashMap.get("seatName"));
                intent.putExtra("seatNum",hashMap.get("seatNum"));
                intent.putExtra("seatPrice",hashMap.get("price"));
                Log.i(TAG, "onItemClick: hashMap = "+hashMap.toString());

                startActivity(intent);
            }
        });

        // 前一天的监听事件，点击前一天按钮，查询前一天车次。并发送Http请求查询前一天的车次数据
        BT1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mday -= 1;
                if( mday <= 0 ){
                    mmonth -= 1;
                    mday = 31;
                }
                startTrainDate = myear+"-"+mmonth+"-"+mday;
                TV8.setText(startTrainDate);
                queryFromServerWithDate(startTrainDate);

            }
        });

        // 后一天的监听事件，点击前一天按钮，查询后一天车次，并发送Http请求查询后一天的车次数据
        BT2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mday += 1;
                if( mday >= 31 ){
                    mmonth += 1;
                    mday = 1;
                }
                startTrainDate = myear+"-"+mmonth +"-"+mday;
                TV8.setText(startTrainDate);
                queryFromServerWithDate(startTrainDate);

            }
        });

        // 让ActiongBar上的返回键显示
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
    }

    // ActionBar上返回键的监听事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch ( item.getItemId()){
            case android.R.id.home:
                chepiaoyuding2Activity.this.finish();
                break;
        }
        return true;
    }


    //  向服务器查询车次数据的Http方法 ，
    public void queryFromServerWithDate(final String date){
        // 进度条显示 ，让用户知道程序在查询中
        final ProgressDialog progressDialog = new ProgressDialog(chepiaoyuding2Activity.this);
        progressDialog.setTitle("加载数据中...");
        progressDialog.show();

        //开启线程查询数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                String JSESSIONID = sharedPreferences.getString("cookie", "");
                Log.i(TAG, "run: "+JSESSIONID);
                OkHttpClient okHttpClient = new OkHttpClient();
                FormBody formBody = new FormBody.Builder().add("fromStationName",fromStationName)
                        .add("toStationName",toStationName)
                        .add("startTrainDate",date)
                        .build();
                Request request = new Request.Builder().url(Constant.Host+"/otn/TrainList").post(formBody).addHeader("cookie",JSESSIONID).build();
                Call call = okHttpClient.newCall(request);
                try {
                    final String string = call.execute().body().string();

                    // 查询到数据后， 先解析成List数组，再调用confData() 将List内的seat获取出来。再将seat内的数据
                    // 加载到组件中
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                           progressDialog.dismiss();
                            if(!string.equals("[]")) {
                                listTrain = new Gson().fromJson(string,new TypeToken<List<Train>>() {}.getType());
                                confData();
                            }else {
                                if(listTrain != null){
                                    dataArray.clear();
                                    myListViewAdapter2.notifyDataSetChanged();
                                }
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void confData(){
        Log.i(TAG, "confData: trainNo"+trainNo);
        for (int i = 0; i < listTrain.size(); i++) {
            Train train = listTrain.get(i);

            if( train.getTrainNo().equals(trainNo)){
                Map<String, Seat> seats = train.getSeats();
                seatUpdate(seats);  // 重新更新组件的方法
            }
        }

    }
    // 重新更新组件的方法
    public void seatUpdate(Map<String,Seat> seats){
        Set<String> keySet = seats.keySet();
        Iterator<String> iterator = keySet.iterator();
        dataArray.clear();
        while ( iterator.hasNext() ){
            Seat seat = seats.get(iterator.next());
            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("seatName",seat.getSeatName());
            hashMap.put("seatNum",seat.getSeatNum()+"张");
            hashMap.put("price","￥ "+seat.getSeatPrice());
            dataArray.add(hashMap);
        }
        Log.i(TAG, "seatUpdate: dataArray:"+dataArray.toString());
        myListViewAdapter2.notifyDataSetChanged();
    }
}